#!/bin/bash

MASTER_USER=${MYSQL_MASTER_USER:-repl}
MASTER_PASSWORD=${MYSQL_MASTER_PASSWORD:-repl@3721}
ROOT_USER="${MYSQL_ROOT_USER:-root}"
ROOT_PASSWORD="${MYSQL_ROOT_PASSWORD:-qingcloudEC@3721}"
MASTER_HOST="${MYSQL_MASTER_HOST:-qingcloud-ec-mysql}"

sleep 10

# shellcheck disable=SC2006
RESULT=`mysql -u"$MASTER_USER" -h"$MASTER_HOST" -p"$MASTER_PASSWORD" -e "SHOW MASTER STATUS;" | grep -v grep |tail -n +2| awk '{print $1,$2}'`

# shellcheck disable=SC2006
LOG_FILE_NAME=`echo $RESULT | grep -v grep | awk '{print $1}'`
# shellcheck disable=SC2006
LOG_FILE_POS=`echo $RESULT | grep -v grep | awk '{print $2}'`

SYNC_SQL="change master to master_host='$MASTER_HOST',master_user='$MASTER_USER',master_password='$MASTER_PASSWORD',master_log_file='$LOG_FILE_NAME',master_log_pos=$LOG_FILE_POS;"
START_SYNC_SQL="start slave;"
STATUS_SQL="show slave status\G;"

mysql -u"$ROOT_USER" -p"$ROOT_PASSWORD" -e "$SYNC_SQL $START_SYNC_SQL $STATUS_SQL"
